<?php
include_once dirname(dirname(__FILE__))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
/**
 * 抽帧图片处理类
 * @author pan.liang
 * @example 
 *      多张图片生成1张图片
 *      image_make::multi_images_to_one_image($arr_image,dirname(__FILE__)."/".np_guid_rand().'/',4,4,'jpg')
 *      1张图片切割成多张图片
 *      image_make::one_image_to_multi_images($arr_image,dirname(__FILE__)."/".np_guid_rand().'/',4,4,'jpg')
 */
class image_make extends m_config
{
    /**
     * 图片支持的类型
     * @var unknown
     */
    public static $arr_image_type = array(
        IMAGETYPE_GIF=>'gif',
        IMAGETYPE_JPEG=>'jpg',
        IMAGETYPE_PNG=>'png',
        IMAGETYPE_BMP=>'bmp',
    );
    
    /**
     * 获取图片的基本信息
     * @param string $file_url 图片的绝对路径
     * @return array:number string Ambigous <NULL, unknown>
     */
    public static function get_image_size($file_url)
    {
        $image_info = @getimagesize($file_url);
        if(!$image_info || !is_array($image_info) || empty($image_info))
        {
            return self::return_data(1,"获取图片信息失败；路径[$file_url]");
        }
        return self::return_data(0,'ok',$image_info);
    }
    
    /**
     * image加载到内存中
     * @param string $file_url 图片的绝对路径
     * @param string $image_info 图片的基本信息 可为空
     * @return array:number string Ambigous <NULL, unknown>
     */
    public static function image_source_create_from_type($file_url,$image_info=null)
    {
        if(!file_exists($file_url))
        {
            return self::return_data(1,"查询原始图片文件不存在，路径[{$file_url}]");
        }
        if($image_info === null)
        {
            $image_info = self::get_image_size($image_info);
            if($image_info['ret'] !=0)
            {
                return $image_info;
            }
            $image_info = $image_info['data_info'];
        }
        if(!isset($image_info[2]) || !$image_info[2] || !in_array($image_info[2], array_keys(self::$arr_image_type)))
        {
            return self::return_data(1,"查询原始图片文件的类型查询失败，原始片源路径[{$file_url}],类型返回值[$image_info[2]],支持的类型有[".implode(";", array_values(self::$arr_image_type))."]");
        }
        switch ($image_info[2])
        {
            case IMAGETYPE_GIF:
                $str_func = 'Imagecreatefromgif';
                break;
            case IMAGETYPE_JPEG:
                $str_func = 'Imagecreatefromjpeg';
                break;
            case IMAGETYPE_PNG:
                $str_func = 'Imagecreatefrompng';
                break;
            case IMAGETYPE_BMP:
                $str_func = 'Imagecreatefromwbmp';
                break;
        }
        $pic_source = @$str_func($file_url);
        if(!$pic_source)
        {
            return self::return_data(1,"查询原始图片文件的类型查询失败，原始片源路径[{$file_url}],内置方法[{$str_func}]");
        }
        return self::return_data(0,'ok',$pic_source);
    }
    
    /**
     * 图片最终生成到本地文件
     * @param object $image_source 图片生成的资源信息 
     * @param string $file_url 图片生成的绝对路径
     * @param string $type 生成的图片格式  比如  jpg、png等 
     * @return array:number string Ambigous <NULL, unknown>
     */
    public static function make_image_source_create_from_type($image_source,$file_url,$type)
    {
        $temp_message_url = $file_url;
        $arr_pathinfo = pathinfo($temp_message_url);
        if(isset($arr_pathinfo['extension']))
        {
            $temp_message_url = (isset($arr_pathinfo['dirname']) && $arr_pathinfo['dirname'] !='.' && $arr_pathinfo['dirname'] !='..') ? trim(trim(trim($arr_pathinfo['dirname'],'\\'),'/')) : '';
        }
        if (!is_dir($temp_message_url))
        {
            mkdir($temp_message_url, 0777, true);
            if(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
            {
                $stat = stat($temp_message_url);
                $result_chown = (posix_getpwuid($stat['uid']));
                if(!isset($result_chown['name']) || $result_chown['name'] != 'www')
                {
                    chown($result_chown, 'www');
                }
            }
        }
        $type = strtolower($type);
        if(!in_array($type, array_values(self::$arr_image_type)))
        {
            return self::return_data(1,"创建图片文件失败，图片类型[$type],支持的类型有[".implode(";", array_values(self::$arr_image_type))."]");
        }
        switch ($type)
        {
            case 'gif':
                $str_func = 'imagegif';
                break;
            case 'jpg':
                $str_func = 'imagejpeg';
                break;
            case 'png':
                $str_func = 'imagepng';
                break;
            case 'bmp':
                $str_func = 'imagewbmp';
                break;
        }
        if(file_exists($file_url))
        {
            unlink($file_url);
        }
        $pic_source = @$str_func($image_source,$file_url);
        if(!$pic_source)
        {
            return self::return_data(1,"创建文件失败");
        }
        return self::return_data(0,'ok');
    }
    
    /**
     * 多个图片转换为一张图片
     * @param array $arr_image 多个图片的绝对路径数组，注意排序
     * @param string $image_dir 最终生成的图片存放地址，如果文件夹里面含有了生成后的图片，会替换掉  注意哈 
     * @param number $num_width 图片合成的X爼个数
     * @param number $num_height 
     * @param string $type
     * @param number $model_width
     * @param number $model_heigh
     */
    public static function multi_images_to_one_image($arr_image,$image_dir,$num_width=4,$num_height=4,$type='jpg',$model_width=0,$model_heigh=0)
    {
        if($num_width <1 || $num_height<1)
        {
            return self::return_data(1,"图片横纵个数<1");
        }
        if(strlen($type)<1)
        {
            return self::return_data(1,"图片类型为空");
        }
        $type = strtolower($type);
        if(!is_array($arr_image) || empty($arr_image))
        {
            return self::return_data(1,"图片数组为空");
        }
        $arr_image = array_values($arr_image);
        if(!is_array($arr_image) || empty($arr_image))
        {
            return self::return_data(1,"图片数组为空");
        }
        $width_height = $num_width*$num_height;
        $arr_image = array_chunk($arr_image, $width_height);
        $arr_multi_image = null;
        $image_dir = rtrim(rtrim(rtrim($image_dir,'\\'),'/'));
        foreach ($arr_image as $key=>$value)
        {
            $image_make = null;
            $arr_image_piece = array_chunk($value, $num_width);
            foreach ($arr_image_piece as $arr_image_url_key=>$arr_image_url_val)
            {
                foreach ($arr_image_url_val as $str_image_url_key=>$str_image_url_val)
                {
                    $result_piece_size = self::get_image_size($str_image_url_val);
                    if($result_piece_size['ret'] !=0)
                    {
                        return $result_piece_size;
                    }
                    $result_piece_source = self::image_source_create_from_type($str_image_url_val,$result_piece_size['data_info']);
                    if($result_piece_source['ret'] !=0)
                    {
                        return $result_piece_source;
                    }
                    if($arr_image_url_key == 0 && $str_image_url_key == 0)
                    {
                        $image_make = imagecreate($num_width*$result_piece_size['data_info'][0], $num_height*$result_piece_size['data_info'][1]);
                    }
                    imagecopy($image_make, $result_piece_source['data_info'],$str_image_url_key*$result_piece_size['data_info'][0],$arr_image_url_key*$result_piece_size['data_info'][1], 0, 0, $result_piece_size['data_info'][0], $result_piece_size['data_info'][1]);
                    unset($temp_piece_source);
                }
            }
            $file_name = str_pad($key+1, 6, "0", STR_PAD_LEFT).".".$type;
            $result_make = self::make_image_source_create_from_type($image_make, $image_dir.'/'.$file_name,$type);
            if($result_make['ret'] !=0)
            {
                return $result_make;
            }
            $arr_multi_image[] = $image_dir.'/'.$file_name;
        }
        return self::return_data(0,'ok',$arr_multi_image);
    }
    
    
    public static function one_image_to_multi_images($arr_image,$image_dir,$num_width=4,$num_height=4,$type='jpg')
    {
        if($num_width <1 || $num_height<1)
        {
            return self::return_data(1,"图片横纵个数<1");
        }
        if(strlen($type)<1)
        {
            return self::return_data(1,"图片类型为空");
        }
        if(!is_array($arr_image) || empty($arr_image))
        {
            return self::return_data(1,"图片数组为空");
        }
        $arr_image = array_values($arr_image);
        if(!is_array($arr_image) || empty($arr_image))
        {
            return self::return_data(1,"图片数组为空");
        }
        $image_dir = rtrim(rtrim(rtrim($image_dir,'\\'),'/'));
        $num = 0;
        $arr_multi_image = null;
        foreach ($arr_image as $image_key=>$image_value)
        {
            $result_piece_size = self::get_image_size($image_value);
            if($result_piece_size['ret'] !=0)
            {
                return $result_piece_size;
            }
            $result_piece_source = self::image_source_create_from_type($image_value,$result_piece_size['data_info']);
            if($result_piece_source['ret'] !=0)
            {
                return $result_piece_source;
            }
            $make_width = floor($result_piece_size['data_info'][0]/$num_width);
            $make_height = floor($result_piece_size['data_info'][1]/$num_height);
            for ($i=0;$i<$num_width;$i++)
            {
                for ($j=0;$j<$num_height;$j++)
                {
                    $num++;
                    $image_make = null;
                    $image_make = imagecreate($make_width, $make_height);
                    $file_name = str_pad($num, 10, "0", STR_PAD_LEFT).".".$type;
                    imagecopy($image_make, $result_piece_source['data_info'],0,0,$i*$make_width,$j*$num_height,$make_width,$make_height);
                    $result_make = self::make_image_source_create_from_type($image_make, $image_dir.'/'.$file_name,$type);
                    if($result_make['ret'] !=0)
                    {
                        return $result_make;
                    }
                    $arr_multi_image[] = $image_dir.'/'.$file_name;
                }
            }
        }
        return self::return_data(0,'ok',$arr_multi_image);
    }
}